<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\common\model;

use buwang\base\BaseModel;
use app\common\model\member\WalletBill;

class Member extends BaseModel
{

    protected $pk = 'id';

    /**
     * 用户信息关联
     * @return void
     */
    public function miniapp()
    {
        return $this->hasOne('MemberMiniapp', 'member_id', 'id');
    }

    /**
     * 用户钱包信息关联
     * @return void
     */
    public function wallet()
    {
        return $this->hasOne(\app\common\model\member\Wallet::class, 'member_id', 'id')->bind(['money', 'freeze_money']);
    }

    /**
     * 添加编辑
     * @param array $param 数组
     */
    public static function edit(array $param)
    {
        $data['phone_id'] = $param['phone_id'];
        $data['username'] = $param['username'];
        $data['lock_config'] = $param['lock_config'];
        $data['login_ip'] = request()->ip();
        $data['login_time'] = time();
        $data['update_time'] = time();
        if (!empty($param['login_password'])) {
            $data['password'] = password_hash(md5($param['login_password']), PASSWORD_DEFAULT);
        }
        if (!empty($param['safe_password'])) {
            $data['safe_password'] = password_hash(md5($param['safe_password']), PASSWORD_DEFAULT);
        }
        if (isset($param['id']) && $param['id'] > 0) {
            return self::where('id', $param['id'])->update($data);
        } else {
            $data['create_time'] = time();
            $data['parent_id'] = 0;
            return self::insert($data);
        }
    }

    /**
     * 添加编辑
     * @param array $param 数组
     */
    public static function bindEdit(array $param)
    {
        $data['phone_id'] = $param['phone_id'];
        $data['username'] = $param['username'];
        $data['password'] = password_hash(md5($param['login_password']), PASSWORD_DEFAULT);
        $data['bind_member_miniapp_id'] = $param['miniapp_id'];
        if (isset($param['id']) && $param['id'] > 0) {
            return self::where('id', $param['id'])->update($data);
        } else {
            $data['parent_id'] = $param['user_id'];
            $data['login_ip'] = request()->ip();
            $data['login_time'] = time();
            $data['update_time'] = time();
            $data['create_time'] = time();
            return self::insert($data);
        }
    }

    /**
     * 更新用户新的手机号
     * @param array $param 数组
     */
    public static function editPhone(array $param)
    {
        $data['phone_id'] = $param['phone_id'];
        $data['update_time'] = time();
        return self::where('id', $param['id'])->update($data);
    }

    /**
     * 用户注册
     * @param array $param 参数
     */
    public static function reg(array $param)
    {
        //判断验证码
        $sms['phone_id'] = $param['phone_id'];
        $sms['sms_code'] = $param['sms_code'];
        $is_sms = widget('common/alisms/isSms', $sms);
        if (!$is_sms) {
            return ['code' => 0, 'message' => "验证码错误"];
        }
        //判断手机号是否重复
        $info = self::where(['phone_id' => $param['phone_id']])->find();
        if (isset($info)) {
            return ['code' => 0, 'message' => '帐号已被注册'];
        }
        //验证码通过
        $data['phone_id'] = $param['phone_id'];
        $data['username'] = $param['username'];
        $data['password'] = password_hash(md5($param['login_password']), PASSWORD_DEFAULT);
        $data['safe_password'] = password_hash(md5('123456'), PASSWORD_DEFAULT);  //设置初始安全密码
        $data['login_time'] = time();
        $data['login_ip'] = request()->ip();
        $data['update_time'] = time();
        $data['create_time'] = time();
        $last_id = self::insertGetId($data);
        if ($last_id) {
            return ['code' => 200, 'message' => '注册成功', 'data' => ['id' => $last_id]];
        }
        return ['code' => 0, 'message' => '帐号登录失败'];
    }

    /**
     * 修改我的密码
     * @access public
     */
    public static function upDatePasspowrd(int $uid, string $safepassword)
    {
        $data['id'] = $uid;
        $data['password'] = password_hash(md5($safepassword), PASSWORD_DEFAULT);
        return self::update($data);
    }

    /**
     * 登录用户
     * @param array $param 更新的用户信息
     */
    public static function login(array $param)
    {
        $condition['phone_id'] = $param['login_id'];
        $condition['is_lock'] = 0;
        $result = self::where($condition)->find();
        if ($result) {
            if (!password_verify(md5($param['login_password']), $result->getAttr('password'))) {
                return FALSE;
            }
            self::updateLogin($result->getAttr('id'));
            return $result;
        }
        return FALSE;
    }

    /**
     * 用户找回密码
     * @param array $param 更新的用户信息
     */
    public static function getPasspord(array $param)
    {
        $condition['phone_id'] = $param['phone_id'];
        $condition['is_lock'] = 0;
        $info = self::where($condition)->find();
        if ($info) {
            $result = self::updateLogin($info->getAttr('id'), $param['login_password']);
            return isset($result) ? $info : false;
        }
        return false;
    }

    /**
     * 验证安全密码
     * @param int $user_id 用户ID
     * @param string $safepassword 验证的安全密码
     */
    public static function checkSafePasspord(int $uid, string $safepassword)
    {
        $info = self::where(['id' => $uid])->find();
        if (password_verify(md5($safepassword), $info->getAttr('safe_password'))) {
            return true;
        }
        return false;
    }

    /**
     * 验证登录密码
     * @param int $user_id 用户ID
     * @param string $password 验证的安全密码
     */
    public static function checkPasspord(int $uid, string $password)
    {
        $info = self::where(['id' => $uid])->find();
        if (password_verify(md5($password), $info->getAttr('password'))) {
            return true;
        }
        return false;
    }

    /**
     * 更新安全密码
     * @param array $param 更新的用户信息
     */
    public static function updateSafePasspord(int $uid, string $safepassword)
    {
        $data['id'] = $uid;
        $data['safe_password'] = password_hash(md5($safepassword), PASSWORD_DEFAULT);
        return self::update($data);
    }

    /**
     * 更新用户登录信息
     * @param integer $uid 用户ID
     */
    protected static function updateLogin($uid, $passpord = null)
    {
        $data = [
            'id' => $uid,
            'login_time' => time(),
            'login_ip' => request()->ip()
        ];
        if (!empty($passpord)) {
            $data['password'] = password_hash(md5($passpord), PASSWORD_DEFAULT);
        }
        return self::update($data);
    }

    /**
     * 锁定用户
     * @param integer $id
     */
    public static function lockUser(int $id)
    {
        $result = self::where(['id' => $id])->find();
        $result->is_lock = $result->is_lock ? 0 : 1;
        if ($result->is_lock) {
            MemberMiniapp::where(['member_id' => $id])->update(['is_lock' => 1]);
        }
        return $result->save();
    }

    /**
     * 用户数量统计(租户)
     */
    public static function addUserTotal($member_id)
    {
        $today = $yesterday = $week = 0;
        $member_miniapp_ids = MemberMiniapp::where('member_id', $member_id)->column('id');
        if (!$member_miniapp_ids) return compact('today', 'yesterday', 'week');
        //得到前七天的时间戳
        $weekBefor = date('Y-m-d', strtotime('-7 day'));
        $weekAfter = date('Y-m-d', strtotime('+1 day'));
        //查询昨天的用户数量
        $yesterday = User::where('member_miniapp_id', 'in', $member_miniapp_ids)->whereDay('create_time', 'yesterday')->count();
        //今天
        $today = User::where('member_miniapp_id', 'in', $member_miniapp_ids)->whereDay('create_time', 'today')->count();
        //前七天
        $week = User::where('member_miniapp_id', 'in', $member_miniapp_ids)->where('create_time', 'between time', [$weekBefor, $weekAfter])->count();
        return compact('today', 'yesterday', 'week');
    }

    /**
     * 用户提现统计
     */
    public static function extractTotal($member_id)
    {
        $today = $yesterday = $week = 0;
        $member_miniapp_ids = MemberMiniapp::where('member_id', $member_id)->column('id');
        if (!$member_miniapp_ids) return compact('today', 'yesterday', 'week');
        //得到前七天的时间戳
        $weekBefor = date('Y-m-d', strtotime('-7 day'));
        $weekAfter = date('Y-m-d', strtotime('+1 day'));
        //查询昨天的提现数量
        $yesterday = UserExtractLog::where('u.member_miniapp_id', 'in', $member_miniapp_ids)->alias('a')->join('user u', 'u.id=a.user_id', 'LEFT')->whereDay('a.createtime', 'yesterday')->where('a.status', '1')->sum('extract_price');
        //今天提现数量
        $today = UserExtractLog::where('u.member_miniapp_id', 'in', $member_miniapp_ids)->alias('a')->join('user u', 'u.id=a.user_id', 'LEFT')->whereDay('a.createtime', 'today')->where('a.status', '1')->sum('extract_price');
        //前七天提现数量
        $week = UserExtractLog::where('u.member_miniapp_id', 'in', $member_miniapp_ids)->alias('a')->join('user u', 'u.id=a.user_id', 'LEFT')->where('a.createtime', 'between time', [$weekBefor, $weekAfter])->where('a.status', '1')->sum('extract_price');
        return compact('today', 'yesterday', 'week');
    }


    /**
     * 用户充值统计
     */
    public static function rechargeTotal($member_id)
    {
        $today = $yesterday = $week = 0;
        $member_miniapp_ids = MemberMiniapp::where('member_id', $member_id)->column('id');
        if (!$member_miniapp_ids) return compact('today', 'yesterday', 'week');
        //得到前七天的时间戳
        $weekBefor = date('Y-m-d', strtotime('-7 day'));
        $weekAfter = date('Y-m-d', strtotime('+1 day'));
        //查询昨天的提现数量
        $yesterday = UserRecharge::where('u.member_miniapp_id', 'in', $member_miniapp_ids)->alias('a')->join('user u', 'u.id=a.uid', 'LEFT')->whereDay('a.add_time', 'yesterday')->where('a.paid', 1)->sum('price');
        //今天提现数量
        $today = UserRecharge::where('u.member_miniapp_id', 'in', $member_miniapp_ids)->alias('a')->join('user u', 'u.id=a.uid', 'LEFT')->whereDay('a.add_time', 'today')->where('a.paid', 1)->sum('price');
        //前七天提现数量
        $week = UserRecharge::where('u.member_miniapp_id', 'in', $member_miniapp_ids)->alias('a')->join('user u', 'u.id=a.uid', 'LEFT')->where('a.add_time', 'between time', [$weekBefor, $weekAfter])->where('a.paid', 1)->sum('price');
        return compact('today', 'yesterday', 'week');
    }

    /**
     * 当前应用数量
     */
    public static function appTotal($member_id)
    {
        return MemberMiniapp::where('member_id', $member_id)->count();
    }

    /**
     * 租户数量统计
     */
    public static function addMemberTotal()
    {
        $today = $yesterday = $week = 0;
        //得到前七天的时间戳
        $weekBefor = date('Y-m-d', strtotime('-7 day'));
        $weekAfter = date('Y-m-d', strtotime('+1 day'));
        //查询昨天的用户数量
        $yesterday = self::whereDay('create_time', 'yesterday')->count();
        //今天
        $today = self::whereDay('create_time', 'today')->count();
        //前七天
        $week = self::where('create_time', 'between time', [$weekBefor, $weekAfter])->count();
        $all = self::count();
        return compact('today', 'yesterday', 'week', 'all');
    }


    /**
     * 用户数量统计(总后台)
     */
    public static function allUserTotal()
    {
        $today = $yesterday = $week = 0;
        //得到前七天的时间戳
        $weekBefor = date('Y-m-d', strtotime('-7 day'));
        $weekAfter = date('Y-m-d', strtotime('+1 day'));
        //查询昨天的用户数量
        $yesterday = User::whereDay('create_time', 'yesterday')->count();
        //今天
        $today = User::whereDay('create_time', 'today')->count();
        //前七天
        $week = User::where('create_time', 'between time', [$weekBefor, $weekAfter])->count();
        $all = User::count();//总数
        return compact('today', 'yesterday', 'week', 'all');
    }


    /**
     * 租户充值统计
     */
    public static function memberRechargeTotal()
    {
        $today = $yesterday = $week = 0;
        //得到前七天的时间戳
        $weekBefor = date('Y-m-d', strtotime('-7 day'));
        $weekAfter = date('Y-m-d', strtotime('+1 day'));
        //查询昨天的用户数量
        $yesterday = WalletBill::whereDay('create_time', 'yesterday')->where('type', 'recharge')->sum('value');
        //今天
        $today = WalletBill::whereDay('create_time', 'today')->where('type', 'recharge')->sum('value');
        //前七天
        $week = WalletBill::where('create_time', 'between time', [$weekBefor, $weekAfter])->where('type', 'recharge')->sum('value');
        $all = WalletBill::where('type', 'recharge')->sum('value');
        return compact('today', 'yesterday', 'week', 'all');
    }

    /**
     * 租户购买应用统计
     */
    public static function memberAppTotal()
    {
        $today = $yesterday = $week = 0;
        //得到前七天的时间戳
        $weekBefor = date('Y-m-d', strtotime('-7 day'));
        $weekAfter = date('Y-m-d', strtotime('+1 day'));
        //查询昨天的用户数量
        $yesterday = MemberMiniapp::whereDay('create_time', 'yesterday')->count();
        //今天
        $today = MemberMiniapp::whereDay('create_time', 'today')->count();
        //前七天
        $week = MemberMiniapp::where('create_time', 'between time', [$weekBefor, $weekAfter])->count();
        $all = MemberMiniapp::count();
        return compact('today', 'yesterday', 'week', 'all');
    }


}